import React, { ReactElement, useRef, useEffect, useContext } from 'react';
import { View, Text, ScrollView, Image, Keyboard } from 'react-native';

import styles, { bottomHeight } from './style';
import { transparentWhiteBack, loginLogo } from '../../../../constant/resource';
import { guestLogin, setScroll, setShowAgreement } from '../../actions';
import Verify from '../Verify';
import Password from '../Password';
import { CHORES_SERVICE_URL, isIOS, PRIVACY_URL } from '../../../../constant';
import Button from '../../../../components/Button';
import { APP_BLUE } from '../../../../constant/color';
import { Store } from '../../reducer';
import navigator from '../../../../util/navigator';
import { getIsOpenGuestEntry } from '../../../../store/appConfig';
import PortraitAlert from '../../../../components/Alert/PortraitAlert';
import { setHasShowAgreement } from '../../../../store/common';
import { systemUtil } from '../../../../util/native';

export default (): ReactElement => {
  const scroll = useRef<ScrollView>(null);
  const containerView = useRef<View>(null);

  const { state } = useContext(Store);
  const { isBind, showAgreement } = state;

  const isOpenGuestEntry = getIsOpenGuestEntry();

  const keyboardWillShow = (event: any): void => {
    const bottom = event.endCoordinates.height;
    if (bottom < bottomHeight) return;

    if (containerView && containerView.current) {
      containerView.current.setNativeProps({
        style: {
          marginTop: bottomHeight - bottom
        }
      });
    }
  };

  const keyboardWillHide = (): void => {
    if (containerView && containerView.current) {
      containerView.current.setNativeProps({
        style: {
          marginTop: 0
        }
      });
    }
  };

  useEffect((): (() => void) => {
    const keyboardWillShowListener = Keyboard.addListener(
      isIOS ? 'keyboardWillShow' : 'keyboardDidShow',
      keyboardWillShow
    );
    const keyboardWillHideListener = Keyboard.addListener(
      isIOS ? 'keyboardWillHide' : 'keyboardDidHide',
      keyboardWillHide
    );
    return (): void => {
      keyboardWillShowListener.remove();
      keyboardWillHideListener.remove();
    };
  }, []);

  useEffect((): void => {
    setScroll(scroll);
  }, []);

  return (
    <View
      style={styles.container}
      ref={containerView}
      onResponderEnd={(): void => {
        Keyboard.dismiss();
      }}
      onStartShouldSetResponder={(): boolean => true}
    >
      <View style={styles.loadContent}>
        <View style={styles.loadCircle} />
        <Text style={styles.hello}>欢迎登录</Text>
        <ScrollView
          keyboardShouldPersistTaps="always"
          ref={scroll}
          style={styles.content}
          pagingEnabled
          horizontal
          showsHorizontalScrollIndicator={false}
          scrollEnabled={false}
        >
          <Verify />
          <Password />
        </ScrollView>
      </View>
      <View style={styles.loadHeader}>
        {isBind ? (
          <Button
            hitSlop={{ left: 20, top: 20, right: 20, bottom: 20 }}
            style={styles.backContent}
            onPress={(): void => {
              navigator.goBack();
            }}
          >
            <Image style={styles.backIcon} source={transparentWhiteBack} />
          </Button>
        ) : (
          <Image style={styles.logo} source={loginLogo} />
        )}

        {!isBind && isOpenGuestEntry && (
          <Button style={styles.guest} onPress={guestLogin}>
            <Text style={styles.guestDesc}>游客登录</Text>
          </Button>
        )}
      </View>
      {showAgreement && (
        <View style={styles.agreement}>
          <PortraitAlert
            title="用户协议和隐私政策"
            sureDesc="同意"
            cancelDesc="暂不使用"
            sureAction={(): void => {
              setShowAgreement(false);
              setHasShowAgreement();
            }}
            cancelAction={systemUtil.exitApp}
          >
            <View>
              <View style={styles.content1}>
                <Text style={styles.contentDesc}>
                  {`       请你务必审慎阅读、充分理解`}
                  “用户协议”和“隐私政策”
                  {`各条款，包括但不限于：为了向你提供个性化教学、在线课堂等服务，我们需要收集你的设备信息、操作日志等个人信息。你可以在“设置”中查看、变更、删除个人信息并管理你的授权。${'\n'}       你可阅读`}
                  <Text
                    onPress={(): void => {
                      navigator.push('WebView', {
                        title: '用户协议',
                        url: CHORES_SERVICE_URL
                      });
                    }}
                    style={{ color: APP_BLUE }}
                  >
                    《用户协议》
                  </Text>
                  和
                  <Text
                    onPress={(): void => {
                      navigator.push('WebView', {
                        title: '隐私政策',
                        url: PRIVACY_URL
                      });
                    }}
                    style={{ color: APP_BLUE }}
                  >
                    《隐私政策》
                  </Text>
                  了解详细信息。如你同意，请点击“同意”开始接受我们的服务。
                </Text>
              </View>
            </View>
          </PortraitAlert>
        </View>
      )}
    </View>
  );
};
